var express = require('express');
var router = express.Router();
/// 引入数据库模块
var _db = require('../mysql.js');
/// 引入全局变量模块
var other = require('../other.js');
/// 引入解析模块
// var cheerio = require('cheerio');

// var fs = require('fs');
// var ejs = require('ejs');


router.get('/', function (req, res, next) {
  // 第一次查询数据库
  _db.query('SELECT * FROM commodity', function (err, results) {
    if (err) {
      throw err;
    } else {
      // res.send("<script>alert('"+req.query.CommodityID+"');</script>")
      if (req.query.CommodityID == 'undefined') {
        res.render('index', { title: 'Express', _username: other._username, DB: results, req: req, ck_two_sql: '0' });
      } else {
        // 第二次查询数据库，将第一次查询的结果作为参数传递
        _db.query('SELECT * FROM commodity WHERE CommodityID = ?', [req.query.CommodityID], function (err, results2) {
          if (err) {
            throw err;
          } else {
            // 渲染模板并传递两个查询结果
            res.render('index', { title: 'Express', _username: other._username, DB: results, DB2: results2, req: req, ck_two_sql: '1' });
          }
        })
      }
    }
  });
});

router.post('/order', function (req, res, next) {
/// 获取到用户输入的内容
  var val = req.body;
  var comID = val._comID; // 获取商品ID
  var comCount = val.count; // 商品数量
  var comTotal = val._comTp; // 商品总金额
  var comState = false;
  _db.query('SELECT * FROM students WHERE StuNum=?', [other._usernum], function (err, results) {
    if (err) {
      throw err;
    } else {
      if (results.length < 1) {
        console.log("未登录");
        res.redirect('/login');
        return;
       } else {
        /// 获取到用户信息
        var stuNum = results[0].StuNum;
        var stuSchoolID = results[0].SchoolID;
        var stuDorm_AreaID = results[0].Dorm_AreaID;
        var stuDorm_BuildID = results[0].Dorm_BuildID;
        var stuDorm_RoomID = results[0].Dorm_RoomID;
        _db.query('INSERT INTO orders(CommodityID,Quantity,Total,State,Time,StuNum,SchoolID,Dorm_AreaID,Dorm_BuildID,Dorm_RoomID) VALUES (?,?,?,?,?,?,?,?,?,?)', [comID, comCount, comTotal, comState, new Date(), stuNum, stuSchoolID, stuDorm_AreaID, stuDorm_BuildID, stuDorm_RoomID], function (err2, results2) {
          if (err) {
            throw err;
          } else {
            /// 跳转根目录
            res.redirect('/userinfo');
          }
        })
      }
    }
  });


  // res.render('login', { title: 'Express' });
});


module.exports = router;
